package net.nagaseyasuhito.nicola.component;

import java.awt.image.BufferedImage;
import java.io.IOException;

import net.nagaseyasuhito.nicola.NicolaWebApplication;
import net.nagaseyasuhito.nicola.entity.Image;

import org.apache.wicket.SharedResources;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.markup.html.DynamicWebResource;
import org.apache.wicket.markup.html.image.resource.BufferedDynamicImageResource;
import org.apache.wicket.util.io.IOUtils;
import org.apache.wicket.util.resource.ResourceStreamNotFoundException;

public class NicolaImageResource extends DynamicWebResource {
	private static final long serialVersionUID = 1L;

	private String name;

	public NicolaImageResource(Image image, int maxSize) {
		this.name = image.getId() + "/" + maxSize + "/" + image.getUpdateTimestamp().getTime();

		SharedResources resources = NicolaWebApplication.get().getSharedResources();
		if(resources.get(NicolaImageResource.class, name, null, Integer.toString(maxSize), false) == null) {
			BufferedDynamicImageResource resource = new BufferedDynamicImageResource();
			try {
				BufferedImage source = image.getContent();
				int width = (int)  (source.getWidth() < source.getHeight() ? maxSize : (double) source.getWidth() / source.getHeight() * maxSize);
				int height = (int) (source.getHeight() < source.getWidth() ? maxSize : (double) source.getHeight() / source.getWidth() * maxSize);

				BufferedImage destination = new BufferedImage(maxSize, maxSize, source.getType());
				destination.createGraphics().drawImage(source.getScaledInstance(width, height, BufferedImage.TYPE_INT_BGR), -(width - maxSize) / 2, -(height - maxSize) / 2, null);

				resource.setImage(destination);
			} catch (IOException e) {
				throw new WicketRuntimeException(e);
			}

			resources.add(NicolaImageResource.class, this.name, null, null, resource);
		}
	}

	
	@Override
	protected ResourceState getResourceState() {
		return new DynamicWebResource.ResourceState() {

			@Override
			public String getContentType() {
				SharedResources resources = NicolaWebApplication.get().getSharedResources();
				BufferedDynamicImageResource resource = (BufferedDynamicImageResource) resources.get(NicolaImageResource.class, NicolaImageResource.this.name, null, null, false);
				return resource.getResourceStream().getContentType();
			}

			@Override
			public byte[] getData() {
				SharedResources resources = NicolaWebApplication.get().getSharedResources();
				BufferedDynamicImageResource resource = (BufferedDynamicImageResource) resources.get(NicolaImageResource.class, NicolaImageResource.this.name, null, null, false);
				try {
					return IOUtils.toByteArray(resource.getResourceStream().getInputStream());
				} catch (IOException e) {
					throw new WicketRuntimeException(e);
				} catch (ResourceStreamNotFoundException e) {
					throw new WicketRuntimeException(e);
				}
			}
			
		};
	}
}
